package com.fourinone.core;

import com.fourinone.utils.Setting;

import javax.management.remote.JMXServiceURL;
import java.util.concurrent.*;

public class PoolExactor { //基类
    private static ThreadPoolExecutor tpe; //綫程池
    private static ScheduledThreadPoolExecutor stpe;//定時執行
    static synchronized ThreadPoolExecutor tpe() {
        if (tpe == null) {
            int corePoolSize = Setting.corePoolSize;
            int maximumPoolSize = Setting.maximumPoolSize;
            TimeUnit unit = TimeUnit.MILLISECONDS;
            long keepAliveTime = Setting.keepAliveTime;
            BlockingQueue<Runnable> waitQueue = new ArrayBlockingQueue<Runnable>(2000); //阻塞隊列
            RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy(); //ThreadPoolExecutor.CallerRunPolicy()
            tpe = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,unit, waitQueue, handler);
        }
        return tpe;
    }
    static ScheduledThreadPoolExecutor stpe () {
        if (stpe == null) {
            int corePoolSize = Setting.corePoolSize;
            stpe = new ScheduledThreadPoolExecutor(corePoolSize);
        }
        return stpe;
    }
    static void execute (Runnable d, Runnable i, long t) {
        tpe().execute(d);
        if (t > 0) {
            stpe().schedule(d, t, TimeUnit.SECONDS);
        }
    }

    /**
     * 保持可見性 保證綫程安全
     */
    static synchronized void close () {
        if (tpe != null) {
            try {
                while (tpe.getActiveCount() > 0) {
                    tpe.shutdown();
                }
                tpe = null;
            } catch (SecurityException se) {
                se.printStackTrace();
            }
        }
        if (stpe != null) {
            try {
                stpe.shutdown();
                stpe = null;
            } catch (SecurityException se) {
                se.printStackTrace();
            }
        }
    }

}
